<template>
	<view class="page">
		<view class="hecswap" :initdata="initdata" :change:initdata="ether.getalldata" :approvestatus="approvestatus"
			:change:approvestatus="ether.approve" :implementid="implementid" :change:implementid="ether.implement">
			<view class="block1">
				<view class="line5">
					<view class="left">
						<image class="image" src="../../static/images/chain/TRON.png" mode="widthFix"></image>
						<view class="text">TRON</view>
					</view>
					<view class="center">
						<image class="image" src="../../static/images/kualian.png" mode="widthFix"></image>
					</view>
					<view class="right">
						<image class="image" src="../../static/images/chain/JumpFinance.png" mode="widthFix"></image>
						<view class="text">JumpFinance</view>
					</view>
				</view>
				<view class="line4">
					<view class="left">余额：{{ Number(Number(usernum).toFixed(4))}}</view>
					<view class="right">
						<view class="text" @tap="ether.getusernum">
							刷新
						</view>
					</view>
				</view>
				<view class="line2">
					<view class="left">
						<image class="tokenicon"
							src="@/static/images/tokenicon/TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6tTRON0.png" mode="widthFix">
						</image>
						<view class="texts">
							<view class="text1">
								USDT
							</view>
							<view class="text2">
								TRON
							</view>
						</view>
					</view>
					<view class="right">
						<uni-easyinput class="numinput" type='number' v-model="num" placeholder="请输入跨链数量" />
					</view>
				</view>
				<view class="toaddress">
					<uni-easyinput class="toaddressinput" type="text" :styles="inputstyles" v-model="toaddress"
						placeholder="请输入接收地址" />
					<image src="/static/images/newimg30.png" class="addIcon" @tap="open"></image>
				</view>
				<view class="line6">
					<view class="button button1" :data-usernum="usernum" :data-num="num" :data-min="min"
						:data-toaddress="toaddress" @tap="ether.cross">
						跨链
					</view>
				</view>
			</view>
			<view class="block2">
				<view class="line">
					<view class="left">最小跨链数量</view>
					<view class="right">{{min}}</view>
				</view>
				<view class="line">
					<view class="left">手续费</view>
					<view class="right">{{fee}}</view>
				</view>
			</view>
			<view class="logBox" v-if="log.length>0">
				<view class="title">
					<text>最近一条记录</text>
					<text class="more" @tap="logPage">更多记录</text>
				</view>
				<clog :data="log[0]"></clog>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getcrossinfo
	} from "@/http/api.js"
	import common from '@/js_sdk/common/common.js'
	export default {
		props: {
			log: {
				type: Array,
				default: []
			},
			selectAddress: {
				type: String,
				default: ""
			},
		},
		data() {
			return {
				...common.config,
				// 用户地址USDT的数量
				usernum: 0,
				// 用户要兑换的代币数量
				num: "",
				// 要兑换到的地址
				toaddress: "",
				// 预授权执行状态
				approvestatus: false,
				// 执行合约的ID
				implementid: "",
				// 输入框的样式
				inputstyles: {
					height: "100px"
				},
				// 跨链手续费
				fee: "0",
				// 最小跨链数量
				min: "0"
			}
		},
		computed: {
			// 同步给rendjs层的数据
			initdata() {
				return {
					addressInfo: this.$store.getters.addressInfo,
					selectedRpc: this.$store.getters.getRpc,
					config: common.config,
				}
			},
		},
		watch: {
			selectAddress(value) {
				this.toaddress = value.split('_')[0]
			}
		},
		created() {
			this.getcrossinfo("5867", this.tronusdt)
		},
		methods: {
			...common.methonds,
			//添加跨链记录
			addCrossLog(hash) {
				this.$emit("addCrossLog", hash)
			},
			getcrossinfo(chain, address) {
				let params = {
					chain: chain,
					address: address
				}
				getcrossinfo(params).then(res => {
					if (res.code == 200) {
						this.min = res.data.min
						this.fee = res.data.fee
					}
				})
			},
			// 获取用户要兑换的代币余额
			getusernum2(data) {
				this.usernum = data
			},
			// 打开授权弹窗
			approveopen() {
				let data = {
					type: "TRONCROSS",
					token: "USDT",
					tip: "使用跨链功能需要对代币进行授权，授权成功后请重新操作。"
				}
				this.$emit("approveopen", data);
			},
			// 打开底部确认弹窗
			openimplement(data) {
				// 重置执行授权的状态，不然下次调用授权就调用不起来了
				let info = {
					type: "TRONCROSS",
					data: data
				}
				this.$emit("executionopen", info)
			},
			// 修改预授权状态
			changeapprovestatus(status) {
				this.approvestatus = status
			},
			// 执行结束以后隐藏加载框同时重置参数
			implementover() {
				this.toaddress = ""
				this.num = ""
			},
			logPage() {
				uni.navigateTo({
					url: `/pages/logPage/logPage`
				})
			},
			//选择接收地址
			open() {
				this.$emit("openselectaddress")
			},
		}
	}
</script>
<script module="ether" lang="renderjs">
	var tronWeb;
	export default {
		props: {
			selectAddress: {
				type: String,
				default: ""
			},
		},
		data() {
			return {
				// 同步过来的初始化数据
				initdata: {},
				// JS注入状态
				jsstatus: false,
				// 数据同步状态
				datastatus: false,
				// 要执行的合约信息
				implementidinfo: "",
				// 要执行的合约ID
				implementid: ""	,//执行的合约方法
				methond:""
			}
		},
		watch: {
			selectAddress(value) {
				this.toaddress = value
			}
		},
		mounted() {
			// 动态引入较大类库避免影响页面展示
			let script = document.createElement('script')
			script.src = 'static/script/newTronWeb.js'
			document.head.appendChild(script)
			script.onload = this.changjsstatus
			// 加这个就是单纯测接收地址符不符合ETH地址要求
			let script2 = document.createElement('script')
			script2.src = 'static/script/ethers-5.2.umd.min.js'
			document.head.appendChild(script2)
		},
		methods: {
			// js同步
			changjsstatus() {
				this.jsstatus = true
				if (this.datastatus == true) {
					this.getusernum()
				}
			},
			// 同步数据
			getalldata(newValue) {
				if (newValue) {
					this.initdata = newValue
					this.datastatus = true
					if (this.jsstatus == true) {
						this.getusernum()
					}
				}
			},
			// 获取usdt余额
			async getusernum() {
				this.$ownerInstance.callMethod('showloading')
				try {
					if (this.initdata.addressInfo.privateKey) {
						let tronWeb = new TronWeb.TronWeb({
							fullHost: this.initdata.selectedRpc,
							privateKey: this.initdata.addressInfo.privateKey
						})
						let oweraddress = tronWeb.defaultAddress.base58
						let tokencontract = await tronWeb.contract(this.initdata.config.erc20abi, this.initdata.config
							.tronusdt)
						let bignum = await tokencontract.balanceOf(oweraddress).call()
						let num = tronWeb.fromSun(bignum.toString())
						this.$ownerInstance.callMethod('getusernum2', num)
					}
				} catch (e) {
					this.$ownerInstance.callMethod('error', "合约执行失败")
				}
				this.$ownerInstance.callMethod('hideloading')

			},
			// 预执行跨链
			async cross(e) {
				let usernum = e.target.dataset.usernum
				let toaddress = e.target.dataset.toaddress
				let min = e.target.dataset.min
				let num = e.target.dataset.num
				let chainId = 5687;
				if (Number(num) <= 0) {
					return this.$ownerInstance.callMethod('error', "请输入跨链数量")
				}
				if (Number(usernum) < Number(num)) {
					return this.$ownerInstance.callMethod('error', "代币数量不足")
				}
				if (toaddress == "") {
					return this.$ownerInstance.callMethod('error', "请输入接收地址")
				}
				if (!ethers.utils.isAddress(toaddress)) {
					return this.$ownerInstance.callMethod('error', "接收地址格式错误")
				}
				if (Number(min) > Number(num)) {
					return this.$ownerInstance.callMethod('error', "跨链数量少于最小跨链数量")
				}
				this.$ownerInstance.callMethod('showloading')
				try {
					let tronWeb = new TronWeb.TronWeb({
						fullHost: this.initdata.selectedRpc,
						privateKey: this.initdata.addressInfo.privateKey
					})
					let address = tronWeb.defaultAddress.base58
					let tokencontract = await tronWeb.contract(this.initdata
						.config.erc20abi, this.initdata.config.tronusdt);
					let allowanceinfo = await tokencontract.allowance(address, this.initdata.config.troncross).call()
					let allowancenum = allowanceinfo.toString()
					if (Number(tronWeb.toSun(num)) > Number(allowancenum)) {
						this.$ownerInstance.callMethod('approveopen')
						this.$ownerInstance.callMethod('hideloading')
						return
					}
					// TRON可以不用构建合约，知道合约的地址和调用的方法就可以构建合约
					// 这样就能知道要签名的data信息
					var parameter = [{
							type: 'address',
							value: this.initdata.config.tronusdt
						}, {
							type: 'uint256',
							value: tronWeb.toSun(num)
						},
						{
							type: 'string',
							value: toaddress
						}, {
							type: 'uint256',
							value: 5867
						},
					];
					let Gaslimit = await tronWeb.transactionBuilder.triggerConstantContract(this.initdata.config
						.troncross, "exchange(address,uint256,string,uint256)", {},
						parameter, address);
					// 这里需要注意一点，ETH是可以直接给Gaslimit赋值到交易信息里的
					// 但我这边试了，得到的结果是错了，所以我目前的结论是构造交易的时候不需要传能量的消耗数量
					// 只能通过方法去预估
					let transaction = await tronWeb.transactionBuilder.triggerSmartContract(this.initdata.config
						.troncross, "exchange(address,uint256,string,uint256)", {},
						parameter, address);
					// 计算带宽费用
					let bandwidth = transaction.transaction.raw_data_hex.length + 2
					let bandcost = bandwidth * this.initdata.config.bandwidthprice
					// 计算能量费用
					let energycost = Gaslimit.energy_used * this.initdata.config.energprice
					// 计算总费用
					// 有很小的一个，这里忽略不记
					let allcost = bandcost + energycost
					this.implementidinfo = transaction
					this.implementid = Date.now()
					let res = {
						from: address,
						to: this.initdata.config.tronusdt,
						value: 0,
						data: transaction.transaction.raw_data.contract[0].parameter.value.data,
						gasLimit: 0,
						gasPrice: 0,
						fee: tronWeb.fromSun(allcost),
						id: this.implementid,
						num: num,
						symbol: "USDT",
						methond: "exchange",
						from_chain_id: "0",
						from_address: address,
						from_contract: this.initdata.config.tronusdt,
						from_amount: num,
						to_chain_id: chainId,
						to_address: toaddress,
						to_contract: this.initdata.config.jumpusdt,
						to_amount: num,
					}
						this.methond = "exchange"
					this.$ownerInstance.callMethod('openimplement', res)
				} catch (e) {
					this.$ownerInstance.callMethod('error', "合约执行失败")
				}
				this.$ownerInstance.callMethod('hideloading')
			},
			// 预授权
			async approve(newValue) {
				if (newValue) {
					this.$ownerInstance.callMethod('showloading')
					try {
						this.$ownerInstance.callMethod('changeapprovestatus', false)
						let tronWeb = new TronWeb.TronWeb({
							fullHost: this.initdata.selectedRpc,
							privateKey: this.initdata.addressInfo.privateKey
						})
						let address = tronWeb.defaultAddress.base58
						var parameter = [{
							type: 'address',
							value: this.initdata.config.troncross
						}, {
							type: 'uint256',
							value: this.initdata.config.approvenum
						}];

						let Gaslimit = await tronWeb.transactionBuilder.triggerConstantContract(this.initdata.config
							.tronusdt, "approve(address,uint256)", {},
							parameter, address);
						let transaction = await tronWeb.transactionBuilder.triggerSmartContract(this.initdata.config
							.tronusdt, "approve(address,uint256)", {},
							parameter, address);
						// 计算带宽费用
						let bandwidth = transaction.transaction.raw_data_hex.length + 2
						let bandcost = bandwidth * this.initdata.config.bandwidthprice
						// 计算能量费用
						let energycost = Gaslimit.energy_used * this.initdata.config.energprice
						// 计算总费用
						let allcost = bandcost + energycost
						this.implementidinfo = transaction
						this.implementid = Date.now()
						let res = {
							from: address,
							to: this.initdata.config.tronusdt,
							value: 0,
							data: transaction.transaction.raw_data.contract[0].parameter.value.data,
							gasLimit: 0,
							gasPrice: 0,
							fee: tronWeb.fromSun(allcost),
							id: this.implementid,
							symbol: "USDT",
							methond: "approve"
						}
						this.methond = "approve"
						this.$ownerInstance.callMethod('openimplement', res)
					} catch (e) {
						this.$ownerInstance.callMethod('error', "合约执行失败")
					}
					this.$ownerInstance.callMethod('hideloading')
				}
			},
			// 去执行
			async implement(newValue) {
				if (newValue && newValue == this.implementid) {
					this.$ownerInstance.callMethod('showloading')
					try {
						let tronWeb = new TronWeb.TronWeb({
							fullHost: this.initdata.selectedRpc,
							privateKey: this.initdata.addressInfo.privateKey
						})
						let info = await this.implementidinfo
						let signedtxn = await tronWeb.trx.sign(this.implementidinfo.transaction)
						let res = await tronWeb.trx.sendRawTransaction(signedtxn);
						let this_ = this
						let interval = setInterval(async function() {
							let calldata = await tronWeb.trx.getTransaction(res.transaction.txID);
							
							if (calldata) {
								if (calldata.ret[0].contractRet == "SUCCESS") {
									console.log(this_.methond)
									if(this_.methond == 'approve'){
										this_.$ownerInstance.callMethod('error', "授权成功,请重新操作")
									}else{
										this_.$ownerInstance.callMethod("addCrossLog", res.transaction.txID)
										this_.$ownerInstance.callMethod('error', "合约执行成功")
										this_.$ownerInstance.callMethod('implementover')
									}
								} else {
									this_.$ownerInstance.callMethod('error', "合约请求失败")
								}
								this_.$ownerInstance.callMethod('hideloading')
								clearInterval(interval)
								this_.getusernum()
							}
						}, 3000)
					} catch (e) {
						this_.$ownerInstance.callMethod('hideloading')
						this.$ownerInstance.callMethod('error', "合约执行失败")
					}

				}
			}
		}
	}
</script>
<style lang="less" scoped>
	.page {
		width: 100vw;
		height: 100%;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		background-color: #F7F7F7;

		.hecswap {
			padding-top: 26upx;
			height: 100%;
			overflow-y: scroll;
			padding-bottom: 100upx;
			box-sizing: border-box;

			.block1 {
				width: 702upx;
				background-color: #fff;
				border-radius: 32upx;
				padding: 24upx 24upx;
				box-sizing: border-box;
				margin: 0upx auto;

				.line1 {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.left {
						font-size: 28upx;
						color: #666666;
					}

					.right {
						display: flex;
						align-items: center;

						.image {
							width: 48upx;
						}

						.text {
							font-size: 28upx;
							color: #666666;
						}
					}
				}

				.line2 {
					width: 654upx;
					height: 140upx;
					background-color: #F7F7F7;
					border-radius: 24upx;
					box-sizing: border-box;
					padding: 26upx 24upx;
					margin-top: 16upx;
					display: flex;
					align-items: center;

					.left {
						display: flex;
						align-items: center;

						.tokenicon {
							width: 72upx;
						}

						.texts {
							.text1 {
								font-size: 36upx;
								color: #333333;
							}

							.text2 {
								font-size: 24upx;
								color: #999999;
								margin-top: 4upx;
							}

							margin-left:24upx;
						}
					}

					.right {
						margin-left: 105upx;

						.numinput {
							height: 64upx;
							background: #fff;
						}
					}
				}

				.line3 {

					.image {
						display: block;
						margin: 0px auto;
						width: 64upx;
						margin-top: 24upx;
					}
				}

				.line4 {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 16upx;
					margin-bottom: 16upx;

					.left {
						font-size: 28upx;
						color: #666666;
					}

					.right {
						display: flex;
						align-items: center;

						.image {
							width: 48upx;
						}

						.text {
							font-size: 28upx;
							color: #666666;
						}

					}
				}

				.line5 {
					width: 654upx;
					height: 140upx;
					background-color: #F7F7F7;
					border-radius: 24upx;
					box-sizing: border-box;
					padding: 26upx 24upx;
					// margin-top: 16upx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.left {
						display: flex;
						align-items: center;

						.image {
							width: 80upx;
						}

						.text {
							margin-left: 20upx;
						}
					}

					.center {
						.image {
							width: 50upx;
						}
					}

					.right {
						display: flex;
						align-items: center;

						.image {
							width: 80upx;
						}

						.text {
							margin-left: 20upx;
						}
					}
				}

				.toaddress {
					width: 654upx;
					background-color: #F7F7F7;
					// height:88upx;
					border-radius: 24upx;
					box-sizing: border-box;
					margin-top: 16upx;
					display: flex;
					padding: 16upx 16upx;

					.toaddressinput {
						height: 56upx;
						font-size: 32upx;
					}

					.addIcon {
						width: 56upx;
						height: 56upx;
					}
				}

				.line6 {
					width: 100%;
					box-sizing: border-box;
					display: flex;
					justify-content: space-between;
					margin-top: 24upx;

					.button {
						width: 100%;
						line-height: 92upx;
						text-align: center;

						color: #fff;
						border-radius: 16upx;
					}

					.button1 {
						background-color: #FFBC42;
					}

					.button2 {
						background-color: #03BAE8;
					}
				}

				.line7box {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.line7 {
						width: 100%;
						line-height: 92upx;
						background-color: #FF760F;
						color: #fff;
						text-align: center;
						border-radius: 16upx;
						margin-top: 24upx;
					}

					.line7:nth-child(2) {
						background-color: #03BAE8;
					}
				}
			}

			.block2 {
				width: 702upx;
				// height:328upx;
				margin: 0upx auto;
				background-color: #fff;
				padding: 6upx 32upx;
				box-sizing: border-box;
				margin-top: 32upx;
				border-radius: 32upx;
				padding-bottom: 30upx;

				.line {
					display: flex;
					justify-content: space-between;
					margin-top: 36upx;

					.left {
						color: #888888;
						font-size: 32upx;
					}

					.right {
						color: #333333;
					}
				}
			}

			.logBox {
				width: 702upx;
				margin: 0 auto;
				padding-bottom: 130upx;

				.title {
					display: flex;
					justify-content: space-between;
					font-size: 32upx;
					color: #131313;
					margin: 28px 0 20upx;

					.more {
						color: #A2A2A2;
						font-size: 28upx;
					}
				}
			}
		}

		.block3 {
			height: 600upx;
			background-color: #fff;
			border-radius: 20upx 20upx 0upx 0upx;

			.line1 {
				text-align: center;
				position: relative;
				padding-top: 32upx;
				padding-bottom: 30upx;

				.text1 {
					font-size: 36upx;
					color: #333333;
				}

				.icon1 {
					width: 48upx;
					height: 48upx;
					position: absolute;
					right: 32upx;
					top: 32upx;
					border-radius: 50%;
					background-color: #EEEEEE;
					text-align: center;
					line-height: 48upx;
				}
			}

			.line2box {
				.line2 {
					display: flex;
					justify-content: space-between;
					padding: 0upx 32upx;
					align-items: center;
					margin-top: 24upx;

					.left {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.image1 {
							width: 72upx;
						}

						.text1 {
							font-size: 32upx;
							color: #4B3E58;
							margin-left: 16upx;
						}
					}

					.right {
						font-size: 40upx;
						color: #4B3E58;
					}
				}
			}

			.line3 {
				width: 686upx;
				line-height: 88upx;
				text-align: center;
				font-size: 28upx;
				color: #fff;
				background: #26CF6D;
				margin: 0px auto;
				margin-top: 40upx;
				border-radius: 18upx;
				margin-top: 44upx;

			}
		}

		.block4 {
			width: 686upx;
			padding: 32upx 56upx;
			border-radius: 48upx;
			box-sizing: border-box;
			background-color: #fff;

			.title {
				font-size: 48upx;
				color: #333333;
				text-align: center;
				border-bottom: 2upx solid #F7F7F7;
				padding-bottom: 32upx;
			}

			.line1 {
				font-size: 28upx;
				color: #545454;
				margin-top: 32upx;
			}

			.line2 {
				margin-top: 16upx;
				height: 96upx;

				.input {
					height: 96upx;
					width: 100%;


				}
			}

			.line3 {
				font-size: 24upx;
				color: #C2C2C2;
				margin-top: 16upx;

				.tip {
					color: red;
				}
			}

			.line4 {
				width: 100%;
				display: flex;
				justify-content: space-between;

				.button {
					width: 271upx;
					height: 92upx;
					line-height: 92upx;
					border-radius: 64upx;
					text-align: center;
					color: #fff;
					margin-top: 48upx;
				}

				.button1 {
					background-color: #03BAE8;
				}

				.button2 {
					background-color: #FF760F;
				}
			}

		}
	}

	/deep/ .uni-easyinput__content {
		height: 100%;
		background-color: #F7F7F7 !important;
	}

	/deep/ .uni-easyinput__content-input {
		font-size: 24rpx; // 设置字体大小    
	}
</style>